/**
 * 全局设备状态管理器
 * 用于管理所有设备的实时状态，包括在线状态、图案播放状态、播放列表等
 */
class DeviceStore {
  constructor() {
    this.devices = new Map() // 设备状态缓存 Map<deviceSn, deviceStatus>
    this.listeners = new Set() // 状态变化监听器集合
    this.mqttConnected = false // MQTT连接状态
    this.heartbeatTimeouts = new Map() // 心跳超时计时器
    this.offlineThreshold = 60000 // 60秒心跳超时阈值
  }

  normalizeDeviceSn(deviceSn) {
    return typeof deviceSn === 'string' ? deviceSn.trim().toLowerCase() : ''
  }

  /**
   * 创建空的设备数据结构
   * @param {string} deviceSn 设备序列号
   * @returns {Object} 空的设备数据
   */
  createEmptyDeviceData(deviceSn) {
    return {
      sn: deviceSn,
      
      // 设备基本状态 (对应 type: "device")
      device: {
        online: false,
        heap: 0,
        version: '',
        wifi_rssi: 0,
        uptime: 0,
        current_pattern: '',
        played_duration: 0,
        playback_status: 'stopped' // playing/paused/stopped
      },
      
      // 播放配置 (对应 type: "playback")
      playback: {
        pattern_name: '',
        speed: 100,
        is_paused: false,
        clear_before_new: true,
        pause_after_complete: false,
        pause_duration: 300,
        playback_mode: 'sequential', // sequential/random/single_loop
        progress: 0,
        current_time: 0,
        paused_time: 0
      },
      
      // 灯光设置 (对应 type: "lightSettings")
      lightSettings: {
        enabled: false,
        mode: 'constant',
        color: '#FFFFFF',
        brightness: 80
      },
      
      // 播放列表 (对应 type: "playlist")
      playlist: {
        patterns: []
      },
      
      // 心跳信息 (简化版)
      heartbeat: {
        online: false,
        ts: 0,
        rssi: 0
      },
      
      // 时间戳
      created_at: Date.now(),
      updated_at: Date.now()
    }
  }

  /**
   * 处理设备响应消息（新版本）
   * @param {string} deviceSn 设备序列号  
   * @param {Object} responseData 响应数据
   */
  handleDeviceResponse(deviceSn, responseData) {
    console.log('[DeviceStore] 收到设备响应:', deviceSn, responseData)

    // 确保设备存在于store中
    if (!this.devices.has(deviceSn)) {
      this.devices.set(deviceSn, this.createEmptyDeviceData(deviceSn))
    }

    const device = this.devices.get(deviceSn)
    
    try {
      // 根据响应类型处理不同的数据
      switch (responseData.type) {
        case 'command_response':
          // 命令执行结果响应
          this.handleCommandResponse(deviceSn, responseData.data)
          break
          
        case 'device':
          // 设备基本信息响应
          this.handleDeviceInfoResponse(deviceSn, responseData.data)
          break
          
        case 'playback':
          // 播放状态响应
          this.handlePlaybackResponse(deviceSn, responseData.data)
          break
          
        case 'lightSettings':
          // 灯光设置响应
          this.handleLightSettingsResponse(deviceSn, responseData.data)
          break
          
        case 'playlist':
          // 播放列表响应
          this.handlePlaylistResponse(deviceSn, responseData.data)
          break
          
        default:
          console.warn('[DeviceStore] 未知响应类型:', responseData.type)
          break
      }
    } catch (error) {
      console.error('[DeviceStore] 处理设备响应失败:', error, responseData)
    }
  }

  /**
   * 处理命令执行结果响应
   * @param {string} deviceSn 设备序列号
   * @param {Object} data 响应数据
   */
  handleCommandResponse(deviceSn, data) {
    const device = this.devices.get(deviceSn)
    
    // 更新命令执行状态
    if (data.command && data.status !== undefined) {
      console.log(`[DeviceStore] 命令 ${data.command} 执行状态:`, data.status)
      
      // 可以在这里添加命令执行状态的UI反馈
      if (data.status === 'success') {
        console.log(`[DeviceStore] 设备 ${deviceSn} 命令 ${data.command} 执行成功`)
      } else if (data.status === 'error') {
        console.error(`[DeviceStore] 设备 ${deviceSn} 命令 ${data.command} 执行失败:`, data.message)
      }
    }
  }

  /**
   * 处理设备基本信息响应 (type: "device")
   * @param {string} deviceSn 设备序列号
   * @param {Object} data 设备信息
   */
  handleDeviceInfoResponse(deviceSn, data) {
    const device = this.devices.get(deviceSn)
    
    // 更新设备状态
    if (data.online !== undefined) {
      device.device.online = data.online
      device.heartbeat.online = data.online
    }
    
    if (data.heap !== undefined) {
      device.device.heap = data.heap
    }
    
    if (data.version) {
      device.device.version = data.version
    }
    
    if (data.wifi_rssi !== undefined) {
      device.device.wifi_rssi = data.wifi_rssi
      device.heartbeat.rssi = data.wifi_rssi
    }
    
    if (data.uptime !== undefined) {
      device.device.uptime = data.uptime
    }
    
    if (data.current_pattern) {
      device.device.current_pattern = data.current_pattern
    }
    
    if (data.played_duration !== undefined) {
      device.device.played_duration = data.played_duration
    }
    
    if (data.playback_status) {
      device.device.playback_status = data.playback_status.toLowerCase()
    }
    
    device.updated_at = Date.now()
    this.devices.set(deviceSn, device)
    
    console.log(`[DeviceStore] 设备 ${deviceSn} 基本信息已更新`)
    this.notifyListeners(deviceSn, device)
  }

  /**
   * 处理播放状态响应
   * @param {string} deviceSn 设备序列号
   * @param {Object} data 播放状态数据
   */
  /**
   * 处理播放配置响应 (type: "playback")
   * @param {string} deviceSn 设备序列号
   * @param {Object} data 播放配置数据
   */
  handlePlaybackResponse(deviceSn, data) {
    const device = this.devices.get(deviceSn)
    
    // 更新播放配置
    if (data.pattern_name) {
      device.playback.pattern_name = data.pattern_name
    }
    
    if (data.speed !== undefined) {
      device.playback.speed = data.speed
    }
    
    if (data.is_paused !== undefined) {
      device.playback.is_paused = data.is_paused
    }
    
    if (data.clear_before_new !== undefined) {
      device.playback.clear_before_new = data.clear_before_new
    }
    
    if (data.pause_after_complete !== undefined) {
      device.playback.pause_after_complete = data.pause_after_complete
    }
    
    if (data.pause_duration !== undefined) {
      device.playback.pause_duration = data.pause_duration
    }
    
    if (data.playback_mode) {
      device.playback.playback_mode = data.playback_mode
    }
    
    if (data.progress !== undefined) {
      device.playback.progress = data.progress
    }
    
    if (data.current_time !== undefined) {
      device.playback.current_time = data.current_time
    }
    
    if (data.paused_time !== undefined) {
      device.playback.paused_time = data.paused_time
    }
    
    device.updated_at = Date.now()
    this.devices.set(deviceSn, device)
    
    console.log(`[DeviceStore] 设备 ${deviceSn} 播放配置已更新`)
    this.notifyListeners(deviceSn, device)
  }

  /**
   * 处理灯光设置响应 (type: "lightSettings")
   * @param {string} deviceSn 设备序列号
   * @param {Object} data 灯光设置数据
   */
  handleLightSettingsResponse(deviceSn, data) {
    const device = this.devices.get(deviceSn)
    
    // 更新灯光设置
    if (data.enabled !== undefined) {
      device.lightSettings.enabled = data.enabled
    }
    
    if (data.mode) {
      device.lightSettings.mode = data.mode
    }
    
    if (data.color) {
      device.lightSettings.color = data.color
    }
    
    if (data.brightness !== undefined) {
      device.lightSettings.brightness = data.brightness
    }
    
    device.updated_at = Date.now()
    this.devices.set(deviceSn, device)
    
    console.log(`[DeviceStore] 设备 ${deviceSn} 灯光设置已更新`)
    this.notifyListeners(deviceSn, device)
  }

  /**
   * 处理播放列表响应 (type: "playlist")
   * @param {string} deviceSn 设备序列号  
   * @param {Object} data 播放列表数据
   */
  handlePlaylistResponse(deviceSn, data) {
    const device = this.devices.get(deviceSn)
    
    // 更新播放列表
    if (data.patterns && Array.isArray(data.patterns)) {
      device.playlist.patterns = data.patterns.filter(pattern => 
        typeof pattern === 'string' && pattern.trim() !== ''
      )
      
      console.log(`[DeviceStore] 设备 ${deviceSn} 播放列表已更新，包含 ${device.playlist.patterns.length} 个模式:`, device.playlist.patterns)
    }
    
    device.updated_at = Date.now()
    this.devices.set(deviceSn, device)
    
    this.notifyListeners(deviceSn, device)
  }

  /**
   * 更新设备在线状态（来自简化心跳）
   * @param {string} deviceSn 设备序列号
   * @param {Object} onlineData 在线状态数据 {online, ts, rssi}
   */
	updateDeviceOnlineStatus(deviceSn, onlineData = {}) {
		if (!deviceSn) {
			console.warn('[DeviceStore] 无效的设备SN，跳过心跳更新')
			return
		}

		const normalizedSn = this.normalizeDeviceSn(deviceSn)
		let key = deviceSn
		let device = this.devices.get(deviceSn)

		if (!device && normalizedSn && deviceSn !== normalizedSn) {
			key = normalizedSn
			device = this.devices.get(normalizedSn)
		}

		console.log(`[DeviceStore] 🔍 更新设备在线状态: ${deviceSn}`, {
			normalizedSn,
			key,
			deviceExists: !!device,
			onlineValue: onlineData.online,
			currentKeys: Array.from(this.devices.keys())
		})

		if (!device) {
			const initialSn = onlineData.topicSn || onlineData.reportedSn || deviceSn
			console.log(`[DeviceStore] 🆕 初始化设备心跳缓存: ${initialSn}`)
			key = normalizedSn || deviceSn
			device = this.createEmptyDeviceData(initialSn)
			this.devices.set(key, device)
		}

		if (onlineData.reportedSn) {
			device.sn = onlineData.reportedSn
		} else if (onlineData.topicSn && !device.sn) {
			device.sn = onlineData.topicSn
		}

		const isOnline = onlineData.online === true || onlineData.online === 1
		device.heartbeat.online = isOnline
		device.device.online = isOnline
		device.heartbeat.ts = onlineData.ts !== undefined ? onlineData.ts : device.heartbeat.ts
		if (onlineData.rssi !== undefined) {
			device.heartbeat.rssi = onlineData.rssi
			device.device.wifi_rssi = onlineData.rssi
		}
		device.updated_at = Date.now()
		
		this.devices.set(key, device)
		this.resetHeartbeatTimeout(key)

		const notifySn = device.sn || onlineData.topicSn || deviceSn
		console.log(`[DeviceStore] ✅ 设备 ${notifySn} 心跳更新完成:`, {
			online: device.heartbeat.online,
			rssi: device.heartbeat.rssi,
			storedKey: key,
			deviceSn: device.sn
		})
		
		this.notifyListeners(notifySn, device)
	}  /**
   * 处理完整的心跳消息（兼容旧版本）
   * @param {string} deviceSn 设备序列号
   * @param {Object} heartbeatData 完整的心跳数据
   */
  updateDeviceHeartbeat(deviceSn, heartbeatData) {
    if (!heartbeatData || !heartbeatData.hb) {
      console.warn(`[DeviceStore] 无效的心跳数据:`, heartbeatData)
      return
    }

    // 转换为新的在线状态格式
    this.updateDeviceOnlineStatus(deviceSn, {
      online: heartbeatData.on || false,
      ts: heartbeatData.ts,
      rssi: heartbeatData.rssi
    })
    
    // 如果有其他设备信息，更新到device字段
    if (heartbeatData.heap !== undefined || heartbeatData.ver) {
      const device = this.devices.get(deviceSn)
      if (device) {
        if (heartbeatData.heap !== undefined) {
          device.device.heap = heartbeatData.heap
        }
        if (heartbeatData.ver) {
          device.device.version = heartbeatData.ver
        }
        device.updated_at = Date.now()
        this.devices.set(deviceSn, device)
      }
    }
  }

  /**
   * 更新设备完整状态（统一的状态更新接口）
   * @param {string} deviceSn 设备序列号
   * @param {Object} statusData 完整的设备状态数据
   */
  updateDeviceStatus(deviceSn, statusData) {
    console.log(`[DeviceStore] 更新设备 ${deviceSn} 完整状态:`, statusData)
    
    // 确保设备存在
    if (!this.devices.has(deviceSn)) {
      this.devices.set(deviceSn, this.createEmptyDeviceData(deviceSn))
    }
    
    const device = this.devices.get(deviceSn)
    
    // 更新各个部分的状态
    if (statusData.device) {
      device.device = {
        ...device.device,
        ...statusData.device
      }
    }
    
    if (statusData.playback) {
      device.playback = {
        ...device.playback,
        ...statusData.playback
      }
    }
    
    if (statusData.lightSettings) {
      device.lightSettings = {
        ...device.lightSettings,
        ...statusData.lightSettings
      }
    }
    
    if (statusData.playlist) {
      device.playlist = {
        ...device.playlist,
        ...statusData.playlist
      }
    }
    
    if (statusData.heartbeat) {
      device.heartbeat = {
        ...device.heartbeat,
        ...statusData.heartbeat
      }
      // 重置心跳超时计时器
      this.resetHeartbeatTimeout(deviceSn)
    }
    
    // 更新时间戳
    device.updated_at = Date.now()
    
    // 保存到缓存
    this.devices.set(deviceSn, device)
    
    // 通知监听器
    this.notifyListeners(deviceSn, device)
    
    console.log(`[DeviceStore] 设备 ${deviceSn} 状态已更新`)
  }

  /**
   * 重置设备心跳超时计时器
   * @param {string} deviceSn 设备序列号
   */
  resetHeartbeatTimeout(deviceSn) {
    if (!deviceSn) return

    const normalizedSn = this.normalizeDeviceSn(deviceSn)
    const key = this.devices.has(deviceSn) ? deviceSn : (this.devices.has(normalizedSn) ? normalizedSn : deviceSn)

    if (this.heartbeatTimeouts.has(key)) {
      clearTimeout(this.heartbeatTimeouts.get(key))
    }

    const timeoutId = setTimeout(() => {
      console.warn(`[DeviceStore] 设备 ${key} 心跳超时`)
			
      const device = this.devices.get(key)
      if (device) {
        device.heartbeat.online = false
        device.device.online = false
        device.updated_at = Date.now()
        this.devices.set(key, device)
        const notifySn = device.sn || key
        this.notifyListeners(notifySn, device)
      }
    }, this.offlineThreshold)

    this.heartbeatTimeouts.set(key, timeoutId)
  }

  /**
   * 添加状态变化监听器
   * @param {Function} callback 回调函数 (deviceSn, status) => void
   * @returns {Function} 取消监听函数
   */
  addListener(callback) {
    this.listeners.add(callback)
    return () => this.listeners.delete(callback)
  }

  /**
   * 通知所有监听器状态变化
   * @param {string} deviceSn 设备序列号
   * @param {Object} status 设备状态
   */
  notifyListeners(deviceSn, status) {
    if (this.listeners.size === 0) {
      console.warn(`[DeviceStore] ⚠️ 没有监听器,设备 ${deviceSn} 状态变化未通知`)
      return
    }
    
    // 防止通知已删除设备的状态变化
    if (!status) {
      console.warn(`[DeviceStore] ⚠️ 设备 ${deviceSn} 状态为空,不通知监听器`)
      return
    }
    
    console.log(`[DeviceStore] 📢 通知 ${this.listeners.size} 个监听器: ${deviceSn} 状态变化`, {
      online: status?.heartbeat?.online || status?.device?.online,
      rssi: status?.heartbeat?.rssi
    })
    
    this.listeners.forEach(callback => {
      try {
        callback(deviceSn, status)
      } catch (error) {
        console.error('[DeviceStore] 监听器执行错误:', error)
      }
    })
  }

  /**
   * 获取设备状态
   * @param {string} deviceSn 设备序列号
   * @returns {Object|undefined} 设备状态
   */
  getDeviceStatus(deviceSn) {
    if (!deviceSn) return undefined
    return this.devices.get(deviceSn) || this.devices.get(this.normalizeDeviceSn(deviceSn))
  }

  /**
   * 获取所有设备状态
   * @returns {Object} 所有设备状态
   */
  getAllDevicesStatus() {
    return Object.fromEntries(this.devices)
  }

  /**
   * 检查设备是否在线
   * @param {string} deviceSn 设备序列号
   * @returns {boolean} 是否在线
   */
  /**
   * 检查设备是否在线
   * @param {string} deviceSn 设备序列号
   * @returns {boolean} 是否在线
   */
  isDeviceOnline(deviceSn) {
    const device = this.getDeviceStatus(deviceSn)
    // 优先检查 heartbeat，其次检查 device.online
    return device?.heartbeat?.online === true || device?.device?.online === true
  }

  /**
   * 获取设备当前播放的图案
   * @param {string} deviceSn 设备序列号
   * @returns {string|null} 当前播放图案文件名
   */
  getCurrentPattern(deviceSn) {
    const device = this.getDeviceStatus(deviceSn)
    return device?.device?.current_pattern || device?.playback?.pattern_name || null
  }

  /**
   * 移除设备状态
   * @param {string} deviceSn 设备序列号
   */
  removeDevice(deviceSn) {
    console.log('[DeviceStore] 移除设备状态:', deviceSn)
    
    // 清除心跳超时计时器
    if (this.heartbeatTimeouts.has(deviceSn)) {
      clearTimeout(this.heartbeatTimeouts.get(deviceSn))
      this.heartbeatTimeouts.delete(deviceSn)
    }
    
    // 从设备映射中删除
    const removed = this.devices.delete(deviceSn)
    
    if (removed) {
      console.log('[DeviceStore] 设备状态已移除:', deviceSn)
      // 通知监听器设备已被移除
      this.notifyListeners(deviceSn)
    }
    
    return removed
  }

  /**
   * 检查设备是否正在播放图案
   * @param {string} deviceSn 设备序列号
   * @returns {boolean} 是否正在播放
   */
  isPatternPlaying(deviceSn) {
    const device = this.getDeviceStatus(deviceSn)
    return device?.device?.playback_status === 'playing'
  }

  /**
   * 获取设备当前播放状态
   * @param {string} deviceSn 设备序列号
   * @returns {string} 播放状态：'playing', 'paused', 'stopped'
   */
  getPlaybackStatus(deviceSn) {
    const device = this.getDeviceStatus(deviceSn)
    return device?.device?.playback_status || 'stopped'
  }

  /**
   * 获取设备播放模式
   * @param {string} deviceSn 设备序列号
   * @returns {string} 播放模式：'sequential'(顺序), 'random'(随机), 'single_loop'(单曲循环)
   */
  getPlaybackMode(deviceSn) {
    const device = this.getDeviceStatus(deviceSn)
    return device?.playback?.playback_mode || 'sequential'
  }

  /**
   * 获取设备灯光设置
   * @param {string} deviceSn 设备序列号
   * @returns {Object|null} 灯光设置信息
   */
  getLightSettings(deviceSn) {
    const device = this.getDeviceStatus(deviceSn)
    return device?.lightSettings || null
  }

  /**
   * 检查设备灯光是否开启
   * @param {string} deviceSn 设备序列号
   * @returns {boolean} 灯光是否开启
   */
  isLightEnabled(deviceSn) {
    const lightSettings = this.getLightSettings(deviceSn)
    return lightSettings?.enabled === true
  }

  /**
   * 获取设备播放配置详细信息
   * @param {string} deviceSn 设备序列号
   * @returns {Object|null} 播放配置信息
   */
  getPlaybackStateDetails(deviceSn) {
    const device = this.getDeviceStatus(deviceSn)
    return device?.playback || null
  }

  /**
   * 获取设备播放设置（用于播放控制面板）
   * @param {string} deviceSn 设备序列号
   * @returns {Object|null} 播放设置信息
   */
  getPlaybackSettings(deviceSn) {
    const device = this.getDeviceStatus(deviceSn)
    if (!device) return null
    
    return {
      speed: device.playback?.speed || 100,
      pause_after_complete: device.playback?.pause_after_complete || false,
      pause_duration: device.playback?.pause_duration || 300,
      clear_before_new: device.playback?.clear_before_new !== undefined ? device.playback.clear_before_new : true,
      playback_mode: device.playback?.playback_mode || 'sequential'
    }
  }

  /**
   * 获取设备播放列表
   * @param {string} deviceSn 设备序列号
   * @returns {Object|null} 播放列表信息 {patterns: string[]}
   */
  getPlaylist(deviceSn) {
    const device = this.getDeviceStatus(deviceSn)
    return device?.playlist || null
  }

  /**
   * 获取播放列表中的图案数量
   * @param {string} deviceSn 设备序列号
   * @returns {number} 图案数量
   */
  getPlaylistCount(deviceSn) {
    const playlist = this.getPlaylist(deviceSn)
    return playlist?.patterns?.length || 0
  }

  /**
   * 获取播放列表中的当前图案索引
   * @param {string} deviceSn 设备序列号
   * @returns {number} 当前图案索引，-1表示无当前图案
   */
  getCurrentPatternIndex(deviceSn) {
    const status = this.getDeviceStatus(deviceSn)
    return status?.playback_state?.current_pattern_index || -1
  }

  /**
   * 获取播放列表中的所有图案
   * @param {string} deviceSn 设备序列号
   * @returns {Array} 图案文件名数组
   */
  getPlaylistPatterns(deviceSn) {
    const playlist = this.getPlaylist(deviceSn)
    const patterns = playlist?.patterns || []
    
    console.log(`[DeviceStore] getPlaylistPatterns for ${deviceSn}:`, patterns)
    return patterns
  }

  /**
   * 检查播放列表是否为空
   * @param {string} deviceSn 设备序列号
   * @returns {boolean} 播放列表是否为空
   */
  isPlaylistEmpty(deviceSn) {
    return this.getPlaylistCount(deviceSn) === 0
  }

  /**
   * 获取设备的最后命令响应
   * @param {string} deviceSn 设备序列号
   * @returns {Object|null} 最后命令响应信息
   */
  getLastCommandResponse(deviceSn) {
    const status = this.getDeviceStatus(deviceSn)
    return status?.lastCommandResponse || null
  }

  /**
   * 清理资源
   */
  destroy() {
    // 清除所有心跳超时计时器
    this.heartbeatTimeouts.forEach(timeoutId => clearTimeout(timeoutId))
    this.heartbeatTimeouts.clear()
    
    // 清空监听器
    this.listeners.clear()
    
    // 清空设备状态
    this.devices.clear()
  }

  /**
   * 工具方法：RGB转十六进制
   * @param {number} r 红色值 (0-255)
   * @param {number} g 绿色值 (0-255)
   * @param {number} b 蓝色值 (0-255)
   * @returns {string} 十六进制颜色
   */
  rgbToHex(r, g, b) {
    if (r === undefined || g === undefined || b === undefined) return '#FFFFFF'
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase()
  }

  /**
   * 工具方法：十六进制转RGB
   * @param {string} hex 十六进制颜色
   * @returns {Object} RGB对象 {r, g, b}
   */
  hexToRgb(hex) {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
    } : { r: 255, g: 255, b: 255 }
  }

  /**
   * 转换模式数值为字符串（兼容旧版本）
   * @param {number} modeValue 模式数值
   * @returns {string} 模式字符串
   */
  convertModeValueToString(modeValue) {
    const modeMap = {
      0: 'constant',
      1: 'breathing', 
      3: 'rainbow',
      10: 'tracking'
    }
    return modeMap[modeValue] || 'constant'
  }

  /**
   * 转换RGB字符串为十六进制颜色（兼容旧版本）
   * @param {string} rgbString RGB字符串 (如 "34,197,93")
   * @returns {string} 十六进制颜色 (如 "#22C55D")
   */
  convertRgbToHex(rgbString) {
    if (!rgbString) return '#FFFFFF'
    
    try {
      // 处理字符串格式的RGB值
      if (typeof rgbString === 'string' && rgbString.includes(',')) {
        const parts = rgbString.split(',').map(part => parseInt(part.trim()))
        if (parts.length === 3 && parts.every(part => !isNaN(part) && part >= 0 && part <= 255)) {
          const [r, g, b] = parts
          return this.rgbToHex(r, g, b)
        }
      }
      
      // 如果已经是十六进制格式，直接返回
      if (typeof rgbString === 'string' && rgbString.startsWith('#')) {
        return rgbString.toUpperCase()
      }
      
      // 默认返回白色
      return '#FFFFFF'
    } catch (error) {
      console.warn('[DeviceStore] 颜色转换失败:', rgbString, error)
      return '#FFFFFF'
    }
  }
}

// 创建全局实例
const deviceStore = new DeviceStore()
export default deviceStore
